package main

import (
	"fmt"
	"github.com/tealeg/xlsx/v3"
	"log"
	"strconv"
	"time"
)

func main() {
	readxlsxFile()
	writerxlsxFile()
}
func readxlsxFile() {
	//读取xlsx 的文件数据
	file, err := xlsx.OpenFile("./fileLearn/fileDir/demoData.xlsx")
	if err != nil {
		log.Printf("open xls err=%s", err)
	}
	//遍历所有的sheet 页
	for index, sheet := range file.Sheets {
		log.Printf("sheet index= %d  name= %v \n", index, sheet.Name)
		//遍历sheet 页面中的每一行
		for i := 0; i < sheet.MaxRow; i++ {
			// 不循环标题行
			if i < 2 {
				continue
			} else {
				//处理每一行中的每一列的数据
				for j := 0; j < sheet.MaxCol; j++ {
					cell, err := sheet.Cell(i, j)
					if err != nil {
						log.Printf("cell xls err=%s \n", err)
					}
					if len(cell.Value) == 0 {
						cell.SetString("此项 为空")
					}
					log.Printf("行 %d 列 %d data=%50s\n", i, j, cell.Value)
				}
			}
		}
	}
}

func writerxlsxFile() {
	//保存到文件位置
	//file := xlsx.NewFile()
	file, err := xlsx.OpenFile("./fileLearn/fileDir/demoData.xlsx")
	if err != nil {
		log.Printf("open xls err=%s", err)
	}

	//添加一个sheet 页
	sheet, err := file.AddSheet(fmt.Sprintf("studentlist_%s", time.Now().Format("2006-01-02-15-04-05")))
	if err != nil {
		fmt.Printf(err.Error())
	}
	stus := getStudents()
	//按照每一行 从左到右的顺序添加数据
	for _, stu := range stus {
		row := sheet.AddRow()

		nameCell := row.AddCell()
		nameCell.Value = stu.Name

		ageCell := row.AddCell()
		ageCell.Value = strconv.Itoa(stu.age)

		phoneCell := row.AddCell()
		phoneCell.Value = stu.Phone

		genderCell := row.AddCell()
		genderCell.Value = stu.Gender

		mailCell := row.AddCell()
		mailCell.Value = stu.Mail
	}
	err = file.Save("./fileLearn/fileDir/demoData.xlsx")
	if err != nil {
		fmt.Printf(err.Error())
	}
	fmt.Println("\n\nexport success")
}

//返回一个学生切片
func getStudents() []Student {
	students := make([]Student, 0)
	for i := 0; i < 10; i++ {
		stu := Student{}
		stu.Name = "name" + strconv.Itoa(i+1)
		stu.Mail = stu.Name + "@chairis.cn"
		stu.Phone = "1380013800" + strconv.Itoa(i)
		stu.age = 20
		stu.Gender = "男"
		students = append(students, stu)
	}
	return students
}

type Student struct {
	Name   string
	age    int
	Phone  string
	Gender string
	Mail   string
}
